<script setup lang="ts">
import { ref } from 'vue'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import CustomNavbar from './components/CustomNavbar.vue'
import HomeSkeleton from './components/HomeSkeleton.vue'

import { getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'
import { getHomeBannerAPI } from '@/services/common'
import type { BannerItem } from '@/types/common'
import type { CategoryItem, HotItem } from '@/types/home'
import type { XtxGuessInstance } from '@/types/component'
import { onLoad } from '@dcloudio/uni-app'
import { useGuessList } from '@/hooks'

// 获取轮播图数据 --------------------
const homeBannerList = ref<BannerItem[]>([])

const getHomeBannerList = async () => {
  const res = await getHomeBannerAPI()
  homeBannerList.value = res.result
}

// 获取分类数据 --------------------
const homeCategoryList = ref<CategoryItem[]>([])
const getHomeCategoryList = async () => {
  const res = await getHomeCategoryAPI()
  homeCategoryList.value = res.result
}

// 获取热门推荐数据 --------------------
const homeHotList = ref<HotItem[]>([])
const getHomeHotList = async () => {
  const res = await getHomeHotAPI()
  homeHotList.value = res.result
}

// 滚动到底部 --------------------
// 猜你喜欢下拉刷新组合式函数
const { xtxGuessRef, handleScrollToLower } = useGuessList()

// 封装获取所有面板数据 -------------------------------------------
const getHomeAllData = async () => {
  await Promise.all([
    getHomeBannerList(),
    getHomeCategoryList(),
    getHomeHotList(),
    xtxGuessRef.value?.getGuessList()
  ])
}

// 下拉刷新 -------------------------
const isTriggered = ref(false) // 下拉刷新状态
const onRefresherrefresh = async () => {
  // 开启动画
  isTriggered.value = true
  // 重置猜你喜欢组件数据
  xtxGuessRef.value?.resetGuessList() // 加载数据

  await getHomeAllData() // 获取所有面板数据
  // 停止动画
  isTriggered.value = false
}

// 调用获取所有面板数据 -------------------------------------------
const isShow = ref(false) // 是否显示骨架屏
onLoad(async () => {
  isShow.value = true // 显示骨架屏
  getHomeAllData()
  isShow.value = false // 隐藏骨架屏
})
</script>

<template>
  <!-- 骨架屏 -->
  <HomeSkeleton v-if="isShow"></HomeSkeleton>
  <!-- 内容 -->
  <template v-else>
    <!-- 导航栏 -->
    <CustomNavbar />
    <scroll-view
      scroll-y
      @scrolltolower="handleScrollToLower"
      @refresherrefresh="onRefresherrefresh"
      :refresher-triggered="isTriggered"
      refresher-enabled
    >
      <!-- 轮播图 -->
      <XtxSwiper :list="homeBannerList"></XtxSwiper>
      <!-- 分类 -->
      <CategoryPanel :list="homeCategoryList"></CategoryPanel>
      <!-- 热门推荐 -->
      <HotPanel :list="homeHotList"></HotPanel>
      <!-- 猜你喜欢 -->
      <XtxGuess ref="xtxGuessRef"></XtxGuess>
    </scroll-view>
  </template>
</template>

<style lang="scss">
/* #ifdef H5 || APP-PLUS */
#app,
/* #endif */
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.scroll-view {
  flex: 1;
}
</style>
